/*
  作者: 劳兆城
  描述: 私有的公用函数, 不对外暴露
*/

import Vue from 'vue'
import axios from 'axios'
import * as Util from './util'

const { ERR_OK } = Util

// 浏览器抛出错误
export const _showError = (str) => {
  throw new Error(str)
}

// 错误信息Message
export const _showErrorMessage = (str) => {
  Vue.prototype.$Message.error(str)
}

// ajax 获取数据
export const _ajaxGet = (url, data) => {
  return new Promise((resolve, reject) => {
    axios.get(url, {
      params: data
    }).then(res => {
      resolve(res.data)
    }).catch(err => {
      resolve(err)
    })
  })
}

// 创建Html的标签
export const _createHtml = (name) => document.createElement(name)

const boxTail = require('./img/boxTail.png')

// 创建地图信息框
export const _createInfoBox = (str = '', className = '') => {
  const el = _createHtml('div')
  el.className = `GykjMap-info ${className}`

  const wrapper = _createHtml('div')
  wrapper.className = 'GykjMap-info-wrapper'

  wrapper.innerHTML = str

  el.append(wrapper)

  const div = _createHtml('div')
  div.className = 'GykjMap-info-boxTail'
  div.innerHTML = `<img src=${boxTail} />`

  el.append(div)

  return el
}

// 判断水务数据是否有真实数据
export const _isWaterRealdata = (item) => {
  let bol = false

  if (typeof item.realtime_data === 'object' && JSON.stringify(item.realtime_data) !== '{}') {
    bol = true
  }

  return bol
}

// 判断水闸、泵站水位趋势
export const _waterOutertrend = (status) => {
  let str = status.replace(' ', '')

  let outerImg = ''

  if (str) {
    let imgUrl = ''

    switch (str) {
      case '涨':
        imgUrl = require('./img/leftReadLegendYellow.png')
        break
      case '平':
        imgUrl = require('./img/leftReadLegendBlue.png')
        break
      case '落':
        imgUrl = require('./img/leftReadLegendGreen.png')
        break
      case '正常':
        imgUrl = require('./img/leftReadLegendBluew.png')
        break
      case '超警戒/汛限':
        imgUrl = require('./img/leftReadLegendRed.png')
        break
    }

    outerImg = `<img class="GykjMap-waterLevel-img" src=${imgUrl} />`
  }

  return outerImg
}

// 水位站、水文站、潮位站、内涝站, 警告图片
export const _waterLevelWarn = (index, alert, level) => {
  if (index === '4' && level > alert) {
    return require('./img/drop_surpass.png')
  }

  if (index === '4' && level <= alert) {
    return require('./img/drop_normal.png')
  }

  if (index === '5' && level > alert) {
    return require('./img/rise_surpass.png')
  }

  if (index === '5' && level <= alert) {
    return require('./img/rise_normal.png')
  }

  if (index === '6' && level > alert) {
    return require('./img/flat_surpass.png')
  }

  if (index === '6' && level <= alert) {
    return require('./img/flat_normal.png')
  }
}

// 获取 class 的 dom 元素
export const _getClassEls = (className) => document.getElementsByClassName(className)

// 过滤时间格式
export const _timeFilter = (time, format) => {
  var o = {
    'M+': time.getMonth() + 1, // month
    'd+': time.getDate(), // day
    'H+': time.getHours(), // hour
    'm+': time.getMinutes(), // minute
    's+': time.getSeconds(), // second
    'q+': Math.floor((time.getMonth() + 3) / 3), // quarter
    'S': time.getMilliseconds() // millisecond
  }

  if (/(y+)/.test(format)) {
    format = format.replace(RegExp.$1, (time.getFullYear() + '').substr(4 - RegExp.$1.length))
  }

  for (var k in o) {
    if (new RegExp('(' + k + ')').test(format)) {
      format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
    }
  }
  return format
}

let elementStyle = document.createElement('div').style

let vendor = (() => {
  let transformNames = {
    webkit: 'webkitTransform',
    Moz: 'MozTransform',
    O: 'OTransform',
    ms: 'msTransform',
    standard: 'transform'
  }

  for (let key in transformNames) {
    if (elementStyle[transformNames[key]] !== undefined) {
      return key
    }
  }

  return false
})()

// 行内样式兼容写法
export const _prefixStyle = (style) => {
  if (vendor === false) {
    return false
  }

  if (vendor === 'standard') {
    return style
  }

  return `-${vendor}-${style}`
}

// 阻止冒泡事件兼容写法
export const _CancelBubble = () => {
  if (window.event.stopPropagation) {
    event.stopPropagation()
  } else {
    window.event.cancelBubble = true
  }
}

function _filterStr (val) {
  return val || '--'
}

// 过滤台风路径基础信息
export const _filterTyphoonBaseInfo = (type, info) => {
  let content = ''
  let title = ''

  if (type === 'point') {
    title = `${_filterStr(info.tfbh)} - ${_filterStr(info.typhoon_name)}`
    content = `
      <span class="typhoon-baseTip-key">过去时间：</span><span class="detail">${_filterStr(_timeFilter(new Date(info.time.replace('T', ' ')), 'yyyy年MM月dd日 HH时'))}</span><br />
      <span class="typhoon-baseTip-key">中心位置：</span><span class="detail">${_filterStr(info.longitude)} °E，${_filterStr(info.latitude)} °N</span><br />
      <span class="typhoon-baseTip-key">最大风力：</span><span class="detail">${_filterStr(info.power)} 级</span><br />
      <span class="typhoon-baseTip-key">最大风速：</span><span class="detail">${_filterStr(info.speed)} 米/秒</span><br />
      <span class="typhoon-baseTip-key">中心气压：</span><span class="detail">${_filterStr(info.pressure)} 百帕</span><br />
      <span class="typhoon-baseTip-key">移动速度：</span><span class="detail">${_filterStr(info.move_speed)} 公里/小时</span><br />
      <span class="typhoon-baseTip-key">移动方向：</span><span class="detail">${_filterStr(info.move_dir)}</span><br />
      <span class="typhoon-baseTip-key">七级风圈半径：</span><span class="detail">${_filterStr(info.radius7)} 公里</span><br />
      <span class="typhoon-baseTip-key">十级风圈半径：</span><span class="detail">${_filterStr(info.radius10)} 公里</span><br />
      <span class="typhoon-baseTip-key">十二级风圈半径：</span><span class="detail">${_filterStr(info.radius12)} 公里</span><br />
    `
  } else if (type === 'dashPoint') {
    title = `[${_filterStr(info.sets)}] ${_filterStr(info.tfbh)} - ${_filterStr(info.typhoon_name)}`
    content = `
      <span class="typhoon-baseTip-key">到达时间：</span><span class="detail">${_filterStr(_timeFilter(new Date(info.time.replace('T', ' ')), 'yyyy年MM月dd日 HH时mm分ss秒'))}</span><br />
      <span class="typhoon-baseTip-key">中心位置：</span><span class="detail">${_filterStr(info.longitude)} °E，${_filterStr(info.latitude)} °N</span><br />
      <span class="typhoon-baseTip-key">最大风力：</span><span class="detail">${_filterStr(info.power)} 级</span><br />
      <span class="typhoon-baseTip-key">最大风速：</span><span class="detail">${_filterStr(info.speed)} 米/秒</span><br />
      <span class="typhoon-baseTip-key">中心气压：</span><span class="detail">${_filterStr(info.pressure)} 百帕</span><br />
      <span class="typhoon-baseTip-key">移动速度：</span><span class="detail">${_filterStr(info.move_speed)} 公里/小时</span><br />
      <span class="typhoon-baseTip-key">移动方向：</span><span class="detail">${_filterStr(info.move_dir)}</span><br />
    `
  }
  return {
    title,
    content,
    local: [+info.longitude, +info.latitude]
  }
}

// 图层自定义数据功能
const customTypeIconError = '自定义图标图层必须传入api路径（apiUrl字段）或者数据（data字段）'
export const _customData = (layerOptions, request) => {
  return new Promise((resolve, reject) => {
    let requestUrl = ''
    let requestData = {}

    if (layerOptions.isCustom === true) {
      if (Array.isArray(layerOptions.data)) {
        resolve(request.callback({
          code: ERR_OK,
          result: layerOptions.data
        }))
        return
      } else if (layerOptions.apiUrl) {
        requestUrl = layerOptions.apiUrl || ''
      } else {
        resolve({
          msg: customTypeIconError
        })
        return
      }
    } else {
      requestUrl = request.url
      requestData = request.data || {}
    }

    _ajaxGet(requestUrl, requestData)
      .then(res => {
        resolve(request.callback(res))
      })
  })
}

// 深拷贝一个Object
export const _cloneObj = (obj) => {
  if (typeof obj !== 'object') {
    return obj
  }
  var s = {}
  if (obj.constructor === Array) {
    s = []
  }
  for (var i in obj) {
    s[i] = _cloneObj(obj[i])
  }
  return s
}
